package com.ruoyi.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.framework.shiro.token.CustomToken;
import com.ruoyi.publish.helper.FileModel;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.HttpRequestUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController {
    @Value("${ruoyi.tokenPath}")
    private String tokenUrl;

    @Autowired
    private ISysUserService userService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(HttpServletRequest request, String username, String password, Boolean rememberMe) {
        // UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);

        // 密码登录
        // CustomToken token=new CustomToken(username);
        CustomToken token = new CustomToken(username, password, rememberMe);


        SavedRequest savedRequest = WebUtils.getSavedRequest(request);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            if (savedRequest != null) {
                String saveUrl = savedRequest.getRequestUrl();
                if (saveUrl.contains("mobile=true")) {
                    return new AjaxResult(AjaxResult.Type.SUCCESSREDIRECT, "success", saveUrl);
                }
            }
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return error("fail");
        }
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }

    //    统计登陆接口
    @GetMapping("/unitlogin")
    public String unitlogin(HttpServletRequest request, String token) throws UnsupportedEncodingException {


        //base64 解码token
        System.out.println("token=" + token);

        Base64.Decoder decoder = Base64.getDecoder();
        String tokenValue = new String(decoder.decode(token), "UTF-8");

        System.out.println("token=" + tokenValue);
        System.out.println("getUserUrl=" + tokenUrl);

        String json;
        String username = null;
        try {
            json = HttpRequestUtil.sendGet(tokenUrl, tokenValue);
            System.out.println(json);

            ObjectMapper mapper = new ObjectMapper();
            try {
//				s productMap = mapper.readValue(json,s.class);
                Map<String, Object> m = mapper.readValue(json, Map.class);
                System.out.println(m);
                if (m.get("username") != null) {
                    String loginName = m.get("username").toString();
                    System.out.println("username=" + loginName);

                    SysUser user = userService.selectUserByLoginName(loginName);
                    if (user != null && user.getUserId() != null) {
                        // UsernamePasswordToken newToken = new UsernamePasswordToken(username, user.getPassword());
                        CustomToken newToken = new CustomToken(loginName);
                        Subject subject = SecurityUtils.getSubject();
                        subject.login(newToken);
                        System.out.println("登陆成功");
                        return "redirect:/index";
                    } else {
                        System.out.println("登陆失败");

                        return "redirect:/login";

                    }

                } else {
                    System.out.println("未获得数据");

                }
                if (m.get("errcode") != null) {
                    System.out.println("返回错误");
                    System.out.println(m.get("errmsg"));
                }
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//转成map
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return "/login";
    }


}

